package com.example.mgsnew.Controller;

import com.example.common.constants.MqConstants;
import com.example.common.domain.Result;
import com.example.mgsnew.Mgs.FileMergeTask;
import com.example.mgsnew.Mgs.UploadProgress;
import com.example.mgsnew.Service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(value = "Mgs文件接口", description = "分片上传大型文件")
@RestController
@RefreshScope//时时刷新配置信息
@Slf4j  //日志  log.info("登录日志测试：");
@RequestMapping("/messages/file")
@RequiredArgsConstructor
public class FileController {
    // 前端分片上传逻辑（示例）
//    function uploadLargeFile(file) {
//    const chunkSize = 10 * 1024 * 1024; // 10MB分片
//    const totalChunks = Math.ceil(file.size / chunkSize);
//
//        for (let i = 0; i < totalChunks; i++) {
//        const start = i * chunkSize;
//        const end = Math.min(start + chunkSize, file.size);
//        const chunk = file.slice(start, end);
//
//            // 发送分片到后端临时存储
//            uploadChunk(chunk, file.name, i, totalChunks);
//        }
//    }
    @Autowired
    private FileService fileService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private static final long MAX_CHUNK_SIZE = 1024 * 1024 * 1024; //1G

    // 后端分片接收接口
    @ApiOperation("上传分片")
    @PostMapping("/upload/chunk")
    public Result<String> receiveChunk(
            @RequestParam("taskId") String taskId,
            @RequestParam("type") String type,
            @RequestParam("chunkIndex") Integer chunkIndex,
            @RequestParam("totalChunks") Integer totalChunks,
            @RequestParam("file") MultipartFile chunk) throws Exception {
        // 文件大小限制检查
        if (chunk.getSize() > MAX_CHUNK_SIZE) {
            return Result.error("分片大小超过限制1G");
        }
        // 存储分片到临时位置（如MinIO或本地目录）
        fileService.saveChunk(taskId, chunkIndex, chunk.getBytes());

        // 当所有分片接收完成后，触发合并任务
        if (chunkIndex == totalChunks - 1) {
            // 发送合并任务到消息队列
            FileMergeTask task = new FileMergeTask();
            task.setTaskId(taskId);
            task.setType(type);
            task.setFileName(chunk.getOriginalFilename());
            task.setTotalChunks(totalChunks);

            fileService.save(task);
            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_FILE,
                    MqConstants.ROUTING_KEY_FILE_MERGE,
                    task);
        }
        return Result.success("分片接收成功");
    }

    @ApiOperation("文件上传进度查询")
    @GetMapping("/upload/progress/{taskId}")
    public Result<UploadProgress> getUploadProgress(@PathVariable String taskId) {
        try {
            // 获取已上传的分片数
            Integer uploadedChunks = fileService.getUploadedChunkCount(taskId);

            // 获取任务信息
            FileMergeTask task = fileService.getTaskFromRedis(taskId);
            if (task == null) {
                return Result.error("任务不存在", UploadProgress.fail(taskId, "任务不存在"));
            }
            // 构建进度信息
            UploadProgress progress = new UploadProgress();
            progress.setTotalChunks(task.getTotalChunks());
            progress.setUploadedChunks(uploadedChunks);
            progress.setProgress((int) (uploadedChunks * 100.0 / task.getTotalChunks()));
            progress.setStatus(task.getStatus());
            progress.setFileUrl(task.getFileUrl());
            progress.setCreateTime(task.getCreateTime());
            progress.setUpdateTime(task.getUpdateTime());
            return Result.success(progress);
        } catch (Exception e) {
            log.error("查询上传进度异常，taskId={}", taskId, e);
            return Result.error("查询进度失败", UploadProgress.fail(taskId, "查询进度失败：" + e.getMessage()));
        }
    }



}
